package com.ficus.road.maintain.core.model;

import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.Assert;

public class GeoNearDocument implements AggregationOperation {

    private Document nearQuery;
    /**
     * 自定义 GeoNear
     * @param query 查询条件
     * @param point 坐标
     * @param distanceField 两点之间的距离字段
     * @param maxDistance  两点之间的最大距离
     */
    public GeoNearDocument(Query query, org.springframework.data.geo.Point point, String distanceField, double maxDistance) {
        Assert.notNull(query, "query must not be null.");
        Assert.notNull(point, "point must not be null.");
        Assert.notNull(point.getX(), "point x must not be null.");
        Assert.notNull(point.getY(), "point y must not be null.");
        Assert.notNull(distanceField, "distanceField must not be null.");
        this.nearQuery = new Document("near", new Document("type", "Point")
                .append("coordinates", new double[]{point.getX(), point.getY()}))
                .append("distanceField", distanceField)
                .append("query", query.getQueryObject())
                .append("maxDistance", maxDistance)
                .append("spherical", true);
    }

    @Override
    public Document toDocument(AggregationOperationContext context) {
        Document command = context.getMappedObject(nearQuery);
        return new Document("$geoNear", command);
    }
}